package com.yc.navy.dayfresh.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.yc.navy.dayfresh.util.ConstantInfo;

/**
 * 创建验证码
 * @author acer
 *
 */
@Controller
public class CreateCodeController{

	@RequestMapping("/getCode")
	public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		String code = getRandomCode();
		System.out.println("------------------------------###");
		//有session
		request.getSession().setAttribute(ConstantInfo.LOGIN_CODE, code);
		
		//生成验证码图片
		BufferedImage image = getCodeImage(code,70,36);
		ImageIO.write(image, "JPEG", response.getOutputStream());
		
	}
	private BufferedImage getCodeImage(String code, int width, int height) {
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		
		//获取这个图片的绘画工具
		Graphics g = image.getGraphics();
		
		//设置绘笔的颜色
		g.setColor(getRandomColor(220, 30)); //0~255
		
		//用背景色绘制一个矩形，大小为图片大小
		g.fillRect(0, 0, width, height);
		
		//绘制干扰线
		Random rd = new Random();
		int x1,y1,x2,y2;
		for(int i=0; i<50; ++ i) {
			x1 = rd.nextInt(width);
			y1 = rd.nextInt(height);
			x2 = rd.nextInt(width);
			y2 = rd.nextInt(height);
			
			g.setColor(getRandomColor(140,60));//设置绘笔的颜色
			g.drawLine(x1, y1, x2, y2);//画直线
		}
		
		g.setFont(new Font("Courier New", Font.ITALIC , 22));
		for(int i = 0, len = code.length(); i<len ; ++ i) {
			g.setColor(getRandomColor(30, 80));
			g.drawString(String.valueOf(code.charAt(i)), 5 + 15 * i, 22);
		}
		return image;
	}
	private Color getRandomColor(int start, int bound) {
		Random rd = new Random();
		int r = start + rd.nextInt(bound);
		int g = start + rd.nextInt(bound);
		int b = start + rd.nextInt(bound);
		return new Color(r, g, b);
	}
	/**
	 * 随机生成验证码
	 * @return
	 */
	private String getRandomCode() {
		Random rd = new Random();
		StringBuffer sbf = new StringBuffer();
		int flag = 0;
		for(int i= 0;i < 4; ++ i) {
			flag = rd.nextInt();
			switch(flag) {
			case 0: sbf.append(rd.nextInt());break;
			case 1: sbf.append((char)(rd.nextInt(26) + 65)); break;
			default:sbf.append((char)(rd.nextInt(26) + 97)); break;
			}
		}
		return sbf.toString();
	}
	
	
}
